package com.reggie.controller;

import com.reggie.pojo.Employee;
import com.reggie.pojo.User;
import com.reggie.service.UserService;
import com.reggie.util.JwtUtil;
import com.reggie.util.ResultUtil;
import com.reggie.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//用户请求映射类
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @PostMapping("/login")
    public ResultUtil<User> login(@RequestBody User u, HttpServletRequest request){
        User user = userService.find(u.getPhone());
        if (user==null) return ResultUtil.error("用户不存在，请重试！");
        System.out.println("1."+user.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("id", String.valueOf(user.getId()));
        map.put("phone", user.getPhone());
        map.put("name", user.getName());
        map.put("avatar", user.getAvatar());
        String token = JwtUtil.genToken(map);
        stringRedisTemplate.opsForValue().set(token, token, 30, TimeUnit.MINUTES);
        request.getSession().setAttribute("userInfo2", token);
        return ResultUtil.success(user);
    }

    @PostMapping("/loginout")
    public ResultUtil<Null> loginout(HttpServletRequest request){
        String token = (String) request.getSession().getAttribute("userInfo2");
        stringRedisTemplate.opsForValue().getOperations().delete(token);
        request.getSession().removeAttribute("userInfo2");
        return ResultUtil.success(null);
    }
}
